<template>
  <rx-layout>
    <div slot="left" width="200" showButton="true">
      <rx-fit>
        <rx-category-treeeditor
          cat-key="BPM"
          read-key="inst.read"
          :edit="false"
          @handSelect="selectTreeNode"
          :async="true"
        ></rx-category-treeeditor>
      </rx-fit>
    </div>
    <div slot="center" style>
      <rx-fit :isheader="isheader">
        <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
          <div v-if="selectedRowKeys.length > 0" class="table-operator">
            <a-button v-if="findAuthRight('inst.delete') && removeEnable" type="danger" icon="delete" @click="delByIds(selectedRowKeys)">
                {{$comi18('rxList.delBtn', '删除')}}
            </a-button>
          </div>
          <span class="search-btn-box" v-if="!isheader">
            <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>
             {{$ti18('rxList.leachBtn','过滤')}}</span>
          </span>
        </div>
        <div  btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel" @close="closeSearchbar">
          <a-form :layout="colLayout">
            <a-row :gutter="24">
              <a-col :span="colSpan">
                <a-form-item :label="i18n('form.billNo','业务单号')">
                  <a-input v-model="queryParam['Q_i.BILL_NO__S_EQ']" :placeholder="i18n('form.billNo','业务单号','input')" />
                </a-form-item>
              </a-col>

              <a-col :span="colSpan" v-if="isheader">
                    <span class="table-page-search-submitButtons">
                      <a-button type="primary"  icon="search" @click="search">
                          {{$ti18('rxList.searchBtn','查询')}}
                      </a-button>
                      <a-button style="margin-left: 4px"  @click="cancel">
                          {{$ti18('rxList.resetBtn','重置')}}
                      </a-button>
                      <a @click="toggleAdvanced" style="margin-left: 8px">
                        {{ advanced ? $ti18('rxList.putAwayBtn','收起') : $ti18('rxList.openBtn','展开') }}
                        <a-icon :type="advanced ? 'up' : 'down'" />
                      </a>
                    </span>
              </a-col>
              <template v-if="advanced">
                  <a-col :span="colSpan">
                <a-form-item :label="i18n('form.timeFrom','创建时间 从')">
                  <a-date-picker
                      :placeholder="i18n('form.createTime','请输入任务创建时间')"
                    v-model="queryParam.Q_CREATE_TIME__D_GE"
                    format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-item>
                  </a-col>
                  <a-col :span="colSpan">
                <a-form-item :label="i18n('form.to','至')">
                  <a-date-picker
                      :placeholder="i18n('form.createTime','请输入任务创建时间')"
                    v-model="queryParam.Q_CREATE_TIME__D_LE"
                    format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-item>
                  </a-col>
                  <a-col :span="colSpan">
                <a-form-item :label="i18n('form.name','标题')">
                  <a-input :placeholder="i18n('form.name','标题','input')" v-model="queryParam.Q_SUBJECT__S_LK" />
                </a-form-item>
                  </a-col>

              </template>
            </a-row>
          </a-form>
        </div>
        <rx-grid
          ref="table"
          bordered
          :allowRowSelect="true"
          :multiSelect="true"
          :columns="columns"
          :defaultPageSize="10"
          url="/api-bpm/bpm/core/bpmInst/myBpmDraftInsts"
          :queryParam="queryParam"
          data-field="result.data"
          :pageSizeOptions="['10', '30', '40']"
          id-field="instId"
          :loadDataOnstart="true"
          @selectChange="onSelectChange"
          :srcoll="{ x: 1000 }"
        >
          <span slot="status" slot-scope="{ text, status }">
            <a-tag :color="statusMap[text].color">
              <span>{{ statusMap[text].text }}</span>
            </a-tag>
          </span>
          <span slot="isLive" slot-scope="{ text,status }">
            <a-tag :color="isLiveMap[text].color">
              <span>{{isLiveMap[text].text}}</span>
            </a-tag>
          </span>
          <span slot="action" slot-scope="{ text, record }" class="actionIcons">
            <span @click.stop="onDetail(record)">{{$ti18('rxList.detailBtn','明细')}}</span>
            <span @click.stop="startFlow(record)">{{i18n('form.enable','启动')}}</span>
            <span v-if="findAuthRight('inst.delete') && removeEnable"
                  @click.stop="delByIds([record.instId])">{{$ti18('rxList.delBtn','删除')}}</span>
          </span>
        </rx-grid>
      </rx-fit>

    </div>
  </rx-layout>
</template>

<script>
import BpmInstApi from '@/api/bpm/core/bpmInst'
import BpmInstLiveSelect from "../core/BpmInstLiveSelect";
import RxCategoryTreeeditor from '@/components/redxun/rx-category-treeeditor'
import { AppBaseList, RxLayout, Util, RxGrid, RxFit } from '@lowcode/jpaas-common-lib'
import FlowUtil from "../js/FlowUtil";

export default {
  name: 'MyBpmInstList',
  mixins: [AppBaseList,FlowUtil],
  components: {
    RxLayout,
    RxGrid,
    RxCategoryTreeeditor,
    RxFit,
  },
  data() {
    return {
      treeData: [],

      cancelVisiable: false,
      cancelInstId: '',
      cancelReason: '', //流程作废原因
      //显示搜索

      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          key: '01',
          title: this.$ti18('rxList.index','序号'),
          type: 'indexColumn',
          dataIndex: 'serial',
          scopedSlots: { customRender: 'serial' },
          width: 80,
        },
        {
          key: '02',
          title: this.i18n('form.name','标题'),
          dataIndex: 'subject',
          width: 200,
        },
        {
          key: '03',
          title:  this.i18n('form.billNo','业务单号'),
          dataIndex: 'billNo',
          width: 110,
        },
        {
          key: '07',
          title: this.i18n('form.creationTime','创建时间'),
          dataIndex: 'createTime',
          width: 160,
        },
        {
          key: '08',
          title:  this.$ti18('rxList.action', '操作'),
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          width: 180,
        },
      ],
      curTree: {},
    }
  },
  methods: {
      i18n(name, text, key) {
          return this.$ti18(name, text, "MyBpmDraft", key);
      },
    selectTreeNode(curRow) {
      this.curTree = curRow
      this.loadData({ 'Q_i.TREE_ID__S_EQ': curRow.treeId })
    },
    onDetail(record) {
      this.openDetail(record.appId,record.instId);
    },
    startFlow(record) {
        this.openInst(record.appId,record.instId);
    },
    restoreInst(record) {
      BpmInstApi.updateProcessStatus(record.instId, 'RUNNING').then((resp) => {
        this.refreshGrid()
      })
    },
    supspendInst(record) {
      BpmInstApi.updateProcessStatus(record.instId, 'SUPSPEND').then((resp) => {
        this.refreshGrid()
      })
    },
    cancelInst(record) {
      this.cancelVisiable = true
      this.cancelInstId = record.instId
    },
    onCancelInst() {
      let self_ = this
      BpmInstApi.cancelProcess(this.cancelInstId, this.cancelReason).then((resp) => {
        self_.cancelReason = ''
        self_.cancelInstId = ''
        self_.cancelVisiable = false
        self_.refreshGrid()
      })
    },
    handleOk() {
      this.$refs.table.loadData()
    },
    delByIds(ids) {
      let self_ = this
      this.$confirm({
          title: this.$ti18('rxMsa.actionTips','操作提示'),
          content: this.$ti18('rxMsa.delInfo','您确定需要删除选中的记录吗？'),
          okText: this.$ti18('rxForm.ackBtn','确认'),
          cancelText: this.$ti18('rxForm.cancelBtn','取消'),
        onOk() {
          BpmInstApi.delBpmInst({ ids: ids.join(',') }).then((res) => {
            if (res.success && res.code == 200) {
              self_.handleOk()
            }
            self_.selectedRowKeys = []
          })
        },
        onCancel() {},
      })
    },
    onLiveProcess(){
      var row=this.$refs.table.getSelectedRow();
      if(!row || (row.status!="SUCCESS_END" && row.status!="ERROR_END")) {
        this.$message.error(this.i18n('tip.unfinished','无法复活未结束的流程！'));
        return;
      }
      if(row.isLive=="YES"){
        this.$message.error(this.i18n('tip.resurrected','无法复活已复活的流程！'));
        return;
      }
      var self_=this;
      Util.open({
        component: BpmInstLiveSelect,
        curVm:this,
        widthHeight:['1024px','600px'],
        title: this.i18n('tip.instance','复活流程实例【')+row.subject+"】",
        data:{
          instId:row.instId
        }
      },function (action,data){
        if(action!='ok')return;
        BpmInstApi.liveProcess({
          actInstId:row.actInstId,
          destNodeUsers:data.destNodeUsers,
          opinion:data.opinion,
          opFiles:data.opFiles
        }).then(res=>{
          self_.refreshGrid();
        })
      });
    },
    search() {
      this.$refs.table.loadData()
    },
    cancel() {
      this.resetSearch()
    },
    closeSearchbar(){
      //关闭过滤弹窗；（点击X触发）
      this.fitSearch = false ;
    },
  },
}
</script>
<style>
</style>
